<!-- 账号管理页 -- 许达 -- 2017年4月16日 -->
<template>
  <div >
    <!-- 查询条件 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;height:46px">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.queryUserName" size="small" placeholder="真实姓名" style="margin-top:4px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.queryLoginName" size="small" placeholder="登录名" style="margin-top:4px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.queryNickName" size="small" placeholder="昵称" style="margin-top:4px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.queryPhone" size="small" placeholder="联系方式" style="margin-top:4px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filters.channel" size="small" placeholder="注册渠道" clearable="">
            <el-option value="0" label="其他"></el-option>
            <el-option value="1" label="官网"></el-option>
            <el-option value="2" label="小程序"></el-option>
            <el-option value="3" label="h5"></el-option>
            <el-option value="4" label="iphone"></el-option>
            <el-option value="5" label="android"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search" size="small" style="line-height:14px">查询</el-button>
        </el-form-item>
        <el-form-item class="button-align">
          <el-button type="danger" @click="batchDelete" :disabled="this.sels.length===0" size="small" v-if="getAuth(0)">批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="accountList" v-loading="listLoading" @selection-change="selsChange" border style="width: 100%; font-size: 12px;" row-class-name="tabRow">
      <el-table-column type="selection" v-if="getAuth(0)"></el-table-column>
      <el-table-column align="center" prop="userName" label="真实姓名" width="115"></el-table-column>
      <el-table-column align="center" prop="loginName" label="登录名" width="115"></el-table-column>
      <el-table-column align="center" prop="nickName" label="昵称" ></el-table-column>
      <el-table-column align="center" :formatter="formatSex" label="性别" width="60"></el-table-column>
      <el-table-column align="center" :formatter="formatCardType" label="证件类型" width="90"></el-table-column>
      <el-table-column align="center" prop="cardNo" label="证件号" ></el-table-column>
      <el-table-column align="center" prop="mail" label="邮箱" ></el-table-column>
      <el-table-column align="center" prop="phone" label="联系方式" width="115"></el-table-column>
      <el-table-column align="center" prop="qq" label="QQ" width="110"></el-table-column>
      <el-table-column align="center" label="状态" width="90">
        <template scope="scope">
          <el-switch v-model="scope.row.status" @change="handleChangeStatus(scope.row)" on-color="#13ce66" off-color="#ff4949" v-if="getAuth(3)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="140px;">
        <template scope="scope">
          <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)" v-if="getAuth(2)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)" v-if="getAuth(1)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="toolbar" style="margin-top: 15px;" v-show="!listLoading">
      <el-pagination id="pagination" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 30]" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="page" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>
    <!--新增/修改弹出层-->
    <el-dialog :title="dialogTitle" v-model="showAdd" :close-on-click-modal="false" @close="resetAccount" >
      <el-form :model="account" label-width="90px" :rules="accountFormRules" ref="account" style="margin-top: -30px;">
        <el-form-item label="登录名" prop="loginName" id="formheight">
          <el-input v-model="account.loginName" :disabled="opType!=='add'"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName" id="formheight">
          <el-input v-model="account.nickName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" id="formheight">
          <el-input v-model="account.password" type="password" ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass" id="formheight">
          <el-input v-model="account.confirmPass" type="password" ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName" id="formheight">
          <el-input v-model="account.userName"></el-input>
        </el-form-item>
        <el-form-item label="证件号" prop="cardNo" id="formheight">
          <el-col :span= "6">
            <el-select v-model="account.cardType" placeholder="请选择" clearable change="handleChange" style="width: 149%;">
              <el-option label="身份证" value="NI"></el-option>
              <el-option label="护照" value="PP" ></el-option>
              <el-option label="其他" value="OTHER"></el-option>
            </el-select>
          </el-col>
          <el-col :span="18" style="padding-left: 35px">
            <el-input v-model="account.cardNo" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" id="formheight">
          <el-radio-group v-model="account.sex">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail" id="formheight">
          <el-input v-model="account.mail" :title="account.mail"></el-input>
        </el-form-item>
        <el-form-item label="QQ" id="formheight">
          <el-input v-model="account.qq"></el-input>
        </el-form-item>
      </el-form>
      <div scope="footer" class="dialog-footer" style="text-align: right;">
        <el-button @click.native="resetAccount">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="saveAccIndexLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import {resetBreads, passwordLevel, sessionOut} from '../../smartlight/common/js/util.js'
  export default {
    data () {
      // 校验两次密码输入是否一致
      var validateConfirmPass = (rule, value, callback) => {
        if (value !== this.account.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      // 校验密码非空判断
      var checkPass = (rule, value, callback) => {
        if (value !== '') {
          if (value.length < 6 || value.length > 18) {
            callback(new Error('请输入6~18个字符'))
          } else if (passwordLevel(value) <= 1) {
            callback(new Error('密码至少包含两种字符'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      // 真实姓名特殊字符验证
      var validateUserName = (rule, value, callback) => {
        var teg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (this.opType === 'add') {
          if (value.trim() === '') {
            callback()
          } else {
            if (teg.test(value)) {
              callback(new Error('请输入正确的真实姓名'))
            } else {
              callback()
            }
          }
        } else {
          if (value.trim() === '') {
            callback(new Error('请输入真实姓名'))
          } else if (teg.test(value)) {
            callback(new Error('请输入正确的真实姓名'))
          } else {
            callback()
          }
        }
      }
      // 证件类型校验规则
      var validateCardType = (rule, value, callback) => {
        var cardType = this.account.cardType
        if (cardType === '' && value !== '') {
          this.account.cardNo = ''
          // callback(new Error('请选择证件类型!'))
        } else if (cardType !== '' && value === '') {
          callback(new Error('请输入证件号!'))
        } else {
          if (cardType === 'NI') {
            var para = {cardNo: value}
            this.$http.post('/smartLight/web/baseAccount/checkIDCard.htm', para).then(response => {
              var resBody = response.body
              if (resBody.isSuccess !== 0) {
                callback(new Error('请输入正确的身份证号码!'))
              } else {
                callback()
              }
            })
          } else if (cardType === 'PP') {
            var teg1 = new RegExp('^[DESPG]\\d{8}$')
            var teg2 = new RegExp('^[DSP]E\\d{7}$')
            if ((!teg1.test(value) && !teg2.test(value)) || value.trim === '') {
              callback(new Error('请输入正确的护照号码!'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      }
      // 证件号校验规则
      var validateCardNo = (rule, value, callback) => {
        var cardType = this.account.cardType
        if (cardType === '') {
          if (value !== '') {
            callback(new Error('请选择证件类型!'))
          } else {
            callback()
          }
        } else if (cardType === 'NI') {
          var para = {cardNo: value}
          this.$http.post('/smartLight/web/baseAccount/checkIDCard.htm', para).then(response => {
            var resBody = response.body
            if (resBody.isSuccess !== 0) {
              callback(new Error('请输入正确的身份证号码!'))
            } else {
              callback()
            }
          })
        } else if (cardType === 'PP') {
          var teg1 = new RegExp('^[DESPG]\\d{8}$')
          var teg2 = new RegExp('^[DSP]E\\d{7}$')
          if ((!teg1.test(value) && !teg2.test(value)) || value.trim === '') {
            callback(new Error('请输入正确的护照号码!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      var validateLoginName = (rule, value, callback) => {
        var teg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        var reg = new RegExp('^1[34578]\\d{9}$')
        if (!reg.test(value)) {
          callback(new Error('登录名格式不正确'))
        } else if (teg.test(value) || value.trim === '') {
          callback(new Error('请输入正确的登录名'))
        } else {
          callback()
        }
      }
      // 校验邮箱格式
      var validateMail = (rule, value, callback) => {
        if (value !== '') {
          var teg = new RegExp('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')
          if (!teg.test(value)) {
            callback(new Error('请输入正确的邮箱!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        saveAccIndexLoading: false,
        addFlag: '',
        addCompany: 'display:none',
        accountList: [],
        total: 2,
        page: 1,
        pageSize: 10,
        count: 0,
        cardTypeArr: {'': '证件类型', 'NI': '身份证', 'PP': '护照', 'OTHER': '其他'},
        filters: {
          queryUserName: '',
          queryLoginName: '',
          queryNickName: '',
          queryPhone: '',
          channel: ''
        },
        id: 0,
        sels: [], // 列表选中列
        listLoading: false,
        showAdd: false,
        addLoading: false,
        showImport: false,
        loginType: 0,
        operateType: 'index',
        fileList: [],
        account: {
          userName: '',
          loginName: '',
          nickName: '',
          cardType: '',
          cardNo: '',
          password: '',
          confirmPass: '',
          sex: 1,
          roleId: '',
          mail: '',
          qq: '',
          status: 0,
          type: 0
        },
        opType: 'add',
        dialogTitle: '新增账号',
        accountFormRules: { // 用户信息校验
          userName: [
            {required: true, message: '请输入真实姓名', trigger: 'blur'},
            {validator: validateUserName, trigger: 'blur'}
          ],
          loginName: [
            {required: true, message: '请输入登录名', trigger: 'blur'},
            {validator: validateLoginName}
          ],
          nickName: [
            {required: true, message: '请输入昵称', trigger: 'blur'}
          ],
          password: [
            {required: false, validator: checkPass, trigger: 'blur'}
          ],
          confirmPass: [
            {required: false, validator: validateConfirmPass, trigger: 'blur'}
          ],
          cardNo: [
            {validator: validateCardNo, trigger: 'blur'},
            {validator: validateCardType, trigger: 'change'}
          ],
          mail: [
            {validator: validateMail, trigger: 'change'}
          ]
        },
        indexAccountButton: [473, 474, 476, 478] // 批量删除、删除、编辑、状态修改
      }
    },
    methods: {
      checkIfLogin () { // 判断是否登录超时
        var user = sessionStorage.getItem('user')
        if (!user) {
          this.$alert('登录超时，请重新登录！', ' ', {
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/login'})
            sessionStorage.clear()
          })
        } else {
          return true
        }
      },
      // 分页插件查询方法-条数
      handleSizeChange (val) {
        this.pageSize = val
        this.initAccountList()
      },
      // 分页插件查询方法-页数
      handleCurrentChange (val) {
        this.page = val
        this.initAccountList()
      },
      // 初始化分页查询用户信息
      initAccountList () {
        this.listLoading = true
        var para = {
          pageNumber: this.page,
          pageSize: this.pageSize,
          userName: this.filters.queryUserName,
          loginName: this.filters.queryLoginName,
          nickName: this.filters.queryNickName,
          phone: this.filters.queryPhone,
          channel: this.filters.channel,
          type: this.loginType,
          op: 'page',
          operateType: this.operateType
        }
        this.$http.post('/smartLight/web/baseAccount/getList.htm', para).then(response => {
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.total = resBody.result.totalElements
            this.accountList = resBody.result.content
            this.listLoading = false
            // autoHeight2() // iframe调整
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      // 状态转换
      formatStatus (row, column) {
        return row.status ? '正常' : '异常'
      },
      // 性别转换
      formatSex (row, column) {
        return row.sex === 1 ? '男' : '女'
      },
      // 证件类型转换
      formatCardType (row, column) {
        return this.cardTypeArr[row.cardType === '' ? ' ' : row.cardType]
      },
      // 【查询】
      search () {
        if (!this.checkIfLogin()) {
          return
        }
        this.page = 1
        this.initAccountList()
      },
      selsChange: function (sels) {
        this.sels = sels
      },
      handleChange: function (val) {
        this.account.cardType = val
      },
      // 【取消】，关闭弹出层
      resetAccount () {
        this.showAdd = false
        this.account = {
          companyId: '',
          userName: '',
          loginName: '',
          cardType: '',
          cardNo: '',
          password: '',
          confirmPass: '',
          sex: 1,
          mail: '',
          qq: ''
        }
        this.$refs['account'].resetFields()
      },
      // 【提交】
      handleSubmit () {
        if (!this.checkIfLogin()) {
          return
        }
        this.$refs.account.validate((valid) => {
          if (valid) {
            var url = '/smartLight/web/baseAccount/updateIndexAccount.htm'
            // 编辑（由于添加和更新的传参方式不同，此处分开处理）
            var params = {
              id: this.account.id,
              loginName: this.account.loginName,
              nickName: this.account.nickName,
              userName: this.account.userName,
              password: this.account.password,
              cardNo: this.account.cardNo,
              cardType: this.account.cardType,
              mail: this.account.mail,
              qq: this.account.qq,
              sex: this.account.sex,
              type: this.loginType,
              accountType: 3
            }
            this.addLoading = true
            this.saveAccIndexLoading = true
            this.doUpdate(url, params)
          }
        })
      },
      // 【编辑】相应后台处理方法
      doUpdate (url, params) {
        this.$http.post(url, params).then(response => {
          this.saveAccIndexLoading = true
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.showAdd = false
            this.addLoading = false
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            })
            this.initAccountList()
            if (this.opType === 'edit') {
              var user = sessionStorage.getItem('user')
              if (user) {
                user = JSON.parse(user)
                if (user.id === this.account.id) { // 修改登录当前的用户，更新用户名
                  sessionStorage.setItem('user', JSON.stringify(this.account))
                  this.$store.dispatch('updateLoginName', this.account.userName)
                }
              }
            }
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      // 【编辑】
      handleEdit (index, row) {
        this.showAdd = true
        this.opType = 'edit'
        this.dialogTitle = '编辑账号'
        this.account = Object.assign({}, row)
        this.account.password = ''
        this.account.confirmPass = ''
      },
      // 【删除】按钮事件
      handleDelete (index, row) {
        var ids = []
        ids.push(row.id)
        this.deleteAccount(ids)
      },

      // 【批量删除】按钮事件
      batchDelete () {
        var ids = []
        this.sels.map(item => {
          ids.push(item.id)
        })
        this.deleteAccount(ids)
      },
      // 【删除】、【批量删除】执行方法
      deleteAccount (ids) {
        if (!this.checkIfLogin()) {
          return
        }
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/smartLight/web/baseAccount/deleteByIds.htm', ids + '|' + this.loginType).then(response => {
            var resBody = response.body
            if (resBody.isSuccess === 0) {
              this.$message({
                showClose: true,
                message: '操作成功',
                type: 'success'
              })
              this.initAccountList()
            } else if (resBody.isSuccess === 2) {
              this.listLoading = false
              sessionOut(this) // session超时处理
            } else {
              this.$message({
                showClose: true,
                message: '操作失败',
                type: 'error'
              })
            }
          })
        }).catch(() => {})
      },
      handleChangeStatus (row) {
        var accountArr = []
        var account = {}
        account.id = row.id
        account.op = 'status'
        var fields = {status: row.status, type: row.type}
        account.fields = fields
        accountArr.push(account)
        this.doUpdate('/smartLight/web/baseAccount/update.htm', accountArr)
      },
      // 获取页面按钮权限
      getAuth (index) {
        if (this.loginType !== 0) { // 供应商/门店
          return false
        } else { // 运营
          let buttonIds = sessionStorage.getItem('buttonIds')
          if (buttonIds === null) {
            return false
          }
          let buttonId = this.indexAccountButton[index]
          if (buttonIds.indexOf(',' + buttonId + ',') >= 0 || buttonIds.indexOf(',' + buttonId) >= 0) {
            return true
          } else {
            return false
          }
        }
      }
    },
    mounted () {
      var user = sessionStorage.getItem('user')
      if (user) {
        user = JSON.parse(user)
        this.loginType = user.type
        // 浏览器向前或向后处理
        resetBreads(this)
        this.initAccountList()
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .tabRow
    font-size: 12px;
  .button-align
    float: right;
  .el-dialog--small
    width: 37% ;
  .prompt
    color: #ff4949
    line-height: 10px !important;
    display: block;

  #formheight
    margin: 14px 0;
    height: 38px;
    .el-form-item__content
      height: 30px;
      .el-form-item__error
        margin-top:3px
    .el-input
      height: 30px;
      .el-input__inner
        height: 30px;

  .borderStyle
    .el-input .el-input__inner {
      border-color: #ff4949 !important;
    }

  #pagination
    background-color: transparent
    .el-input__inner
      width: 120px
</style>
